using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FreeImageAPI;
using System.IO;
using System.Diagnostics;
using System.Net;

namespace WindowsApplication1
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //set default values
            cboSelectImageType.SelectedItem = "GIF";
            cboConvertTo.SelectedItem = "TXT";
        }

        private void Convert()
        {
            StreamReader outputStream = StreamReader.Null;
            string output = "";
            bool success = false;
            StreamWriter inputStream = StreamWriter.Null;
            uint handle = 0;

            try
            {
                if (txtSelectImageFolder.Text == "")
                {
                    MessageBox.Show("Please select image folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (txtSelectDestinationFolder.Text == "")
                {
                    MessageBox.Show("Please enter SharePoint site.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //dirname contains the image folder
                    string dirname = txtSelectImageFolder.Text;//@"D:\Temp\images";
                    //dir contains the system temp folder
                    string dir = Environment.GetEnvironmentVariable("TEMP");
                    DirectoryInfo newDir = new DirectoryInfo(dir);
                    
                    string destPBMDir = dir + "\\pbm"; //the destination pbm directory
                    string destTXTDir = dir + "\\txt"; //the destination txt directory

                    newDir.CreateSubdirectory("pbm"); //create the pbm directory in the temp folder
                    newDir.CreateSubdirectory("txt"); //create the txt directory in the temp folder

                    DirectoryInfo dire = new DirectoryInfo(dirname); //get context of the images folder
                    FileInfo[] fyles = dire.GetFiles("*." + cboSelectImageType.Text); //get all the images from the image folder

                    //declare some variables needed to hold data
                    string strPath;
                    
                    //string strFile;
                    string strFileNameWithOutExtension;
                    string txtFileName;
                    
                    ////////////////////////////////////////////
                    //Convert images to pbm files
                    ////////////////////////////////////////////
                    
                    //read each image from the images folder
                    foreach (FileInfo f in fyles)
                    {
                        strPath = dirname + "\\" + f.Name;
                        strFileNameWithOutExtension = f.Name.Remove(f.Name.LastIndexOf("."));
                        
                        switch (cboSelectImageType.Text)
                        { 
                            case "BMP":
                                
                            //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_BMP,
                                    strPath,
                                    0);
                            
                                break;

                            case "CUT":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_CUT,
                                    strPath,
                                    0);

                                break;
                            
                            case "DDS":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_DDS,
                                    strPath,
                                    0);

                                break;

                            case "GIF":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_GIF,
                                    strPath,
                                    0);

                                break;

                            case "ICO":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_ICO,
                                    strPath,
                                    0);

                                break;

                            case "IFF":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_IFF,
                                    strPath,
                                    0);

                                break;

                            case "JNG":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_JNG,
                                    strPath,
                                    0);

                                break;
                                
                            case "JPEG":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_JPEG,
                                    strPath,
                                    0);

                                break;

                            case "JPG":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_JPEG,
                                    strPath,
                                    0);

                                break;

                            case "KOALA":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_KOALA,
                                    strPath,
                                    0);

                                break;

                            case "LBM":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_LBM,
                                    strPath,
                                    0);

                                break;

                            case "MNG":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_MNG,
                                    strPath,
                                    0);

                                break;

                            case "PBM":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PBM,
                                    strPath,
                                    0);

                                break;

                            case "PBMRAW":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PBMRAW,
                                    strPath,
                                    0);

                                break;

                            case "PCD":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PCD,
                                    strPath,
                                    0);

                                break;

                            case "PCX":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PCX,
                                    strPath,
                                    0);

                                break;

                            case "PGM":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PGM,
                                    strPath,
                                    0);

                                break;

                            case "PGMRAW":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PGMRAW,
                                    strPath,
                                    0);

                                break;

                            case "PNG":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PNG,
                                    strPath,
                                    0);

                                break;

                            case "PPM":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PPM,
                                    strPath,
                                    0);

                                break;

                            case "PPMRAW":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PPMRAW,
                                    strPath,
                                    0);

                                break;

                            case "PSD":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_PSD,
                                    strPath,
                                    0);

                                break;

                            case "RAS":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_RAS,
                                    strPath,
                                    0);

                                break;

                            case "TARGA":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_TARGA,
                                    strPath,
                                    0);

                                break;
                            
                            case "TIFF":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_TIFF,
                                    strPath,
                                    0);

                                break;

                            case "WBMP":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_WBMP,
                                    strPath,
                                    0);

                                break;

                            case "XBM":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_XBM,
                                    strPath,
                                    0);

                                break;

                            case "XPM":

                                //get the handle
                                handle = FreeImageAPI.FreeImage.Load(
                                    FreeImageAPI.FIF.FIF_XPM,
                                    strPath,
                                    0);

                                break;

                            default:
                                break;
                        }

                        //save to pbm
                        FreeImageAPI.FreeImage.Save(
                            FreeImageAPI.FIF.FIF_PBM,
                            handle,
                            destPBMDir + "\\" + strFileNameWithOutExtension + ".pbm",
                            0);

                        //release the handle
                        FreeImageAPI.FreeImage.Unload(handle);

                    }

                    //Get pbm files
                    DirectoryInfo pbmDir = new DirectoryInfo(destPBMDir);
                    FileInfo[] pbmFiles = pbmDir.GetFiles("*.*"); //get the collection of pbm files

                    //Start new process
                    Process newProcess = new Process();

                    //Set process parameters
                    newProcess.StartInfo.FileName = "gocr044";
                    newProcess.StartInfo.UseShellExecute = false;
                    newProcess.StartInfo.CreateNoWindow = true;
                    newProcess.StartInfo.RedirectStandardOutput = true;

                    ///////////////////////////////////////////
                    //Convert pbm files to text files
                    //////////////////////////////////////////

                    //read each pbm file
                    foreach (FileInfo pbmFile in pbmFiles)
                    {
                        //pass pbm file name as argument to the process
                        //newProcess.StartInfo.Arguments = pbmFile.Name;
                        txtFileName = pbmFile.Name.Remove(pbmFile.Name.LastIndexOf("."));

                        //pass pbm file name as argument to the process
                        newProcess.StartInfo.Arguments = " -i " + "\"" + destPBMDir + "\\" + pbmFile.Name + "\"" + " -o " + "\"" + destTXTDir + "\\" + txtFileName + ".txt" + "\"";
                        
                        //start the process
                        newProcess.Start();

                        //set timeout
                        int timeoutSeconds = 10;

                        if (0 == timeoutSeconds)
                        {
                            //get output
                        //    outputStream = newProcess.StandardOutput;
                          //  output = outputStream.ReadToEnd();
                            newProcess.WaitForExit();
                        }
                        else
                        {
                            //wait for the process to exit
                            success = newProcess.WaitForExit(timeoutSeconds * 1000);

                            //if (success)
                            //{
                            //    //get the output
                            //    outputStream = newProcess.StandardOutput;
                            //    output = outputStream.ReadToEnd();

                            //}
                            //else
                            //{
                            //    //throw error
                            //    output = "Timed out at " + timeoutSeconds + " seconds waiting for application to exit.";
                            //}
                        }

                        //Get file name without extension
                        //txtFileName = pbmFile.Name.Remove(pbmFile.Name.LastIndexOf("."));
                        ////Create a text file and save output
                        //inputStream = File.CreateText(destTXTDir + "\\" + txtFileName + ".txt");
                        //inputStream.Write(output);
                        //inputStream.Close();

                        ////close output stream
                        //outputStream.Close();

                    }
                    //MessageBox.Show(output);

                    //release the process object
                    newProcess.Close();
                    newProcess.Dispose();

                    //Upload txt files
                    string msgStatus = Upload(destTXTDir, false);

                    //check for the original source flag and upload original files also
                    //if the flag is set
                    if (chkUploadOriginal.Checked == true)
                        msgStatus += Environment.NewLine + Upload(dirname, true);


                    //Delete pbm directory
                    if (pbmDir.Exists)
                        pbmDir.Delete(true);

                    //Delete txt directory
                    DirectoryInfo txtDir = new DirectoryInfo(destTXTDir);
                    if (txtDir.Exists)
                        txtDir.Delete(true);

                    //discard directory objects
                    newDir = null;
                    pbmDir = null;
                    txtDir = null;

                    //Display approp. messages to the users
                    if (fyles.Length < 1)
                        MessageBox.Show("No files found for conversion! Source directory may not contain the images of the type selected. Please select correct image type.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else  if (pbmFiles.Length < 1)
                        MessageBox.Show("Application failed to convert files.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    else
                        //MessageBox.Show(pbmFiles.Length + " files were converted successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        MessageBox.Show(msgStatus, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                //throw (new Exception("An error occurred running application.", ex));
                MessageBox.Show(ex.Source + " - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                
            }
        }

        public string Upload(string dirname, bool isDir)
        {
            try
            {
                WSFileConvertor.sp.Files oUploader = new WSFileConvertor.sp.Files();
                string msgStatus = "";

                if (txtEnterServiceURL.Text == "")
                {
                    msgStatus = "Please enter web service url.";
                }
                else
                {
                    oUploader.Url = txtEnterServiceURL.Text; // "http://sp/docs/documents/_vti_bin/Files.asmx";
                }

                oUploader.PreAuthenticate = true;
                oUploader.Credentials = CredentialCache.DefaultCredentials;

                //string dirname = dir; // @"D:\Temp\testtest";

                //dirname is the source folder
                DirectoryInfo dire = new DirectoryInfo(dirname);
                FileInfo[] fyles;
                if (isDir)
                {
                    fyles = dire.GetFiles("*." + cboSelectImageType.Text);
                }
                else
                {
                    fyles = dire.GetFiles("*.*");
                }
                string strPath;
                string strFile;
                //string strDestination = "";

                foreach (FileInfo f in fyles)
                {
                    strPath = dirname + "\\" + f.Name;
                    strFile = strPath.Substring(strPath.LastIndexOf("\\") + 1);

                    //strDestination = "http://sp/Docs/Documents";

                    FileStream fStream = new FileStream(strPath, System.IO.FileMode.Open);
                    byte[] binFile = new byte[(int)fStream.Length];
                    fStream.Read(binFile, 0, (int)fStream.Length);
                    fStream.Close();
                    // strFile = "apple";
                    string str = oUploader.UploadDocument(strFile, binFile, txtSelectDestinationFolder.Text);


                }
                //string strPath = @"D:\Temp\Test Document.doc";
                if (fyles.GetUpperBound(0) != -1)
                {
                    msgStatus = fyles.Length + " files successfully uploaded to " + txtSelectDestinationFolder.Text;
                }

                //if (sDelete == "1")
                //{
                //    foreach (FileInfo fi in fyles)
                //    {
                //        fi.Delete();
                //    }
                //}

                return msgStatus;
            }
            catch (Exception ex)
            {
                return ex.Source + " - " + ex.Message;
            }
        }

        private void btnSelectImageFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtSelectImageFolder.Text = folderBrowserDialog1.SelectedPath;
            }

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show("WS-FileConvertor 1.0c converts image files to text readable formats. Developed by: S.S. Ahmed (http://sharepointblogs.com/ssa)","WS-FileConvertor 1.0c",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSelectDestinationFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtSelectDestinationFolder.Text = folderBrowserDialog1.SelectedPath;
            }

        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            Convert();
        }

        //private void txtSelectDestinationFolder_LostFocus(object sender, EventArgs e)
        //{
        //    txtEnterServiceURL.Text = txtSelectDestinationFolder.Text;
        //}

        
        ///////////////////////
    }
}
